from sqlalchemy.orm import Session
from models import OperationLog
from schemas import OperationLogCreate
from typing import Optional


def log_operation(
    db: Session,
    user_id: Optional[int],
    username: Optional[str],
    ip_address: Optional[str],
    operation_type: str,
    operation_content: str,
    success: int = 1,
    error_message: Optional[str] = None
) -> OperationLog:
    """
    记录操作日志
    
    Args:
        db: 数据库会话
        user_id: 用户ID
        username: 用户名
        ip_address: IP地址
        operation_type: 操作类型
        operation_content: 操作内容描述
        success: 操作是否成功，1表示成功，0表示失败
        error_message: 错误信息（可选）
    
    Returns:
        创建的操作日志对象
    """
    log_data = OperationLogCreate(
        user_id=user_id,
        username=username,
        ip_address=ip_address,
        operation_type=operation_type,
        operation_content=operation_content,
        success=success,
        error_message=error_message
    )
    
    db_log = OperationLog(**log_data.dict())
    db.add(db_log)
    db.commit()
    db.refresh(db_log)
    
    return db_log